<template>
	<view>
		<navbar :backshow="true" :title="title" :navBarHeight="navBarHeight" :menuRight="menuRight" :menuTop="menuTop"
			:menuHeight="menuHeight"></navbar>
		<!-- 头部展位 -->
		<view class="main" :style="{ height: mainheight + 'px' }"></view>
		<!-- table -->
		<view class="tabbox">
			<view class="tabboxitem" :class="{ active: activeTab === 0 }" @click="setActiveTab(0)">
				预约选择
			</view>

			<view class="tabboxitem" :class="{ active: activeTab === 1 }" @click="setActiveTab(1)">
				预约记录
			</view>

			<!-- 下划线标识 -->
			<view class="underline" :style="{ left: underlineLeft }"></view>
		</view>
		<!-- 对应table -->
		<view v-show="activeTab === 0" class="yyitembox">
			<view class="bookxqbox">
				<uni-forms :modelValue="formData" ref="customForm" :rules="customRules">
					<view class="devboxs">
						<view class="nme">设备：</view>
						<view class="devitems">
							<view class="devitemsss">
								<uni-forms-item v-for="(item, index) in dynamicLists" :key="item.id"
									:label="item.deviceName" :name="'domains[' + item.id + ']'">
									<view class="devitemssss">
										<uni-number-box :value="1" :step="1" v-model="item.number" />
										<!-- <uni-easyinput v-model="dynamicFormData.domains[item.id]" placeholder="请输入域名" /> -->
										<view class="delclas" @click="del(item.id)">删除</view>
									</view>
								</uni-forms-item>
							</view>
							<view class="tjjys" @click="add">添加借用设备</view>
						</view>
					</view>

					<uni-forms-item label="借用时间" name="datetimerange">
						<!-- <uni-datetime-picker v-model="single" :clearIcon="false" /> -->
						<uni-datetime-picker v-model="formData.datetimerange" type="datetimerange" rangeSeparator="至" />
					</uni-forms-item>

					<uni-forms-item label="备注" name="remark">
						<uni-easyinput type="text" v-model="formData.remark" placeholder="请输入备注" />
					</uni-forms-item>
				</uni-forms>
				<view class="savatj" @click="save">提交信息</view>
			</view>
		</view>
		<view v-show="activeTab === 1" class="yyitembox">
			<view class="yyitem" v-for="item in roombookings" :key="item.appointmentId" @click="yxroomfn(item)">
				<view class="yybst" :class="{
            yybstyyz: item.auditStatus === 1,
            yybstyjs: item.auditStatus === 2,
            yybstwks: item.auditStatus === 9,
          }">
					{{
            item.auditStatus === 1
              ? "已通过"
              : item.auditStatus === 2
              ? "不通过"
              : item.auditStatus === 9
              ? "预约中"
              : item.auditStatus === 11
              ? "已过期"
              : "未知状态"
          }}
				</view>
				<view class="yydesod">
					<view class="yytime">
						<view class="yytimeitem">预约人：</view>
						<view class="yytimeitems">{{ item.createUser }}</view>
					</view>
					<view class="yytime">
						<view class="yytimeitem">预约设备：</view>
						<view class="yytimeitems">
							{{ formattedDeviceNames(JSON.parse(item.deviceDetail)) }}
						</view>
					</view>
					<view class="yytime">
						<view class="yytimeitem">时间：</view>
						<view class="yytimeitems">
							{{ formatTimeRange(item.startTime, item.endTime) }}
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 弹窗 -->
		<!-- 普通弹窗 -->
		<uni-popup ref="popup" background-color="#fff" class="dfdf">
			<uni-popup-dialog :type="msgType" cancelText="取消" confirmText="确认" title="选择您需要借用的设备"
				@confirm="dialogConfirm">
				<view class="ser">
					<uni-search-bar placeholder="搜索您借用的设备" bgColor="#EEEEEE" @confirm="search" @input="search"
						v-model="deviceName" />
				</view>
				<view class="devboxmain">
					<view class="devboxmains">
						<view class="devitem" v-for="item in devlist" :key="item.deviceId"
							:class="devitemid == item.deviceId ? 'devitemhover' : ''" @click="devfn(item)">
							{{ item.deviceName }}
						</view>
					</view>
				</view>
				<view class="inputsb">
					<view class="inputsbqt">其他:</view>
					<uni-easyinput class="uni-mt-5" trim="all" v-model="valuedeviceName"
						placeholder="请输入设备名"></uni-easyinput>
				</view>
			</uni-popup-dialog>
			<!-- <view class="popup-content" :class="{ 'popup-height':'center' }">
				<view class="titletc">
					选择您需要借用的设备
				</view>
				<view class="ser">
					<uni-search-bar placeholder="搜索您借用的设备" bgColor="#EEEEEE" @confirm="search" />
				</view>
			</view> -->
		</uni-popup>
		<uni-popup ref="message" type="message">
			<uni-popup-message type="error" message="还未添加设备" :duration="2000"></uni-popup-message>
		</uni-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				yxdev: "",
				valuedeviceName: "",
				devitemid: 0,
				title: "预约设备",
				navBarHeight: 0, // 导航栏高度
				menuRight: 0, // 胶囊距右方间距（方保持左、右间距一致）
				menuTop: 0, // 胶囊距底部间距（保持底部间距一致）
				menuHeight: 0, // 胶囊高度（自定义内容可与胶囊高度保证一致）
				mainheight: 0,
				activeTab: 0,
				formData: {
					datetimerange: [],
				},
				underlineLeft: "25%",
				dynamicLists: [],
				devlist: [],
				deviceName: "",
				roombookings: [],
				customRules: {
					datetimerange: {
						rules: [{
							required: true,
							errorMessage: "请选择时间",
						}, ],
					},
				},
			};
		},
		computed: {},
		onLoad() {
			const that = this;

			// 获取系统信息
			const systemInfo = wx.getSystemInfoSync();
			// 胶囊按钮位置信息
			const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
			// 导航栏高度 = 状态栏高度 + 44
			that.navBarHeight = systemInfo.statusBarHeight + 44;
			that.menuRight = systemInfo.screenWidth - menuButtonInfo.right;
			that.menuTop = menuButtonInfo.top;
			that.menuHeight = menuButtonInfo.height;
			that.mainheight = menuButtonInfo.top + menuButtonInfo.height;
			// 获取一下 最新数据

			uni.getStorage({
				key: "deviceData",
				success: (res) => {
					console.log("获取的数据：", res.data);
					// 可以在这里处理获取到的数据
					// this.formData = res.data;
					// this.getuser();
					if (res.data.deviceDetail.length > 0) {
						this.dynamicLists = res.data.deviceDetail;
						this.formData.datetimerange.push(res.data.startTime);
						this.formData.datetimerange.push(res.data.endTime);
						this.formData.remark = res.data.remark;
					}
				},
				fail: function() {
					console.error("获取数据失败");
				},
			});
			this.$myRequest({
				url: "/client/appointment/deviceList",
				method: "GET",
			}).then((res) => {
				this.devlist = res.data;
				// console.log("设备列表", res.data);
			});
		},
		watch: {
			activeTab: {
				handler(i) {
					if (i == 0) {
						// this.roomListfn();
					}
					if (i == 1) {
						this.devL();
					}
				},
				immediate: true,
				deep: true,
			},
		},
		onReachBottom() {
			this.pageNum = this.pageNum + 1;
			this.roombookingfns();
			console.log("触底函数");
		},
		methods: {
			yxroomfn(item) {
				if (item.auditStatus != 11) {
					uni.setStorage({
						key: "deviceDataxq",
						data: {
							deviceDetail: JSON.parse(item.deviceDetail),
							startTime: item.startTime,
							endTime: item.endTime,
							remark: item.remark,
							auditStatus: item.auditStatus,
							appointmentId: item.appointmentId,
						},
						success: () => {
							uni.navigateTo({
								url: "/pages/devbookxq/devbookxq", // 要跳转的非 tabBar 页面路径，可以带参数
							});
							console.log("数据存储成功");
						},
					});
				}
				console.log("选择的数据13", item);
			},
			formattedDeviceNames(items) {
				return items.map((item) => item.deviceName).join(", ");
			},
			devL() {
				this.$myRequest({
					url: "/client/appointment/deviceAppointmentRecord",
					method: "GET",
				}).then((res) => {
					console.log("设备预约记录", res.data);
					// this.deviceName = ''
					this.roombookings = res.data.list;
					// console.log("设备列表", res.data);
				});
			},
			save() {
				if (this.dynamicLists.length == 0) {
					console.log("还未添加设备");
					this.messageText = `还未添加设备`;
					this.$refs.message.open();
				} else {
					this.$refs.customForm
						.validate()
						.then((res) => {
							console.log("日期", this.formData.datetimerange);
							uni.setStorage({
								key: "deviceData",
								data: {
									deviceDetail: this.dynamicLists,
									startTime: this.formData.datetimerange[0],
									endTime: this.formData.datetimerange[1],
									remark: this.formData.remark,
								},
								success: function() {
									console.log("数据存储成功");
									uni.navigateTo({
										url: "/pages/devsave/devsave", // 要跳转的非 tabBar 页面路径，可以带参数
									});
								},
							});
						})
						.catch((err) => {
							console.log("表单错误信息：", err);
						});
				}
			},
			dialogConfirm() {
				console.log("添加设备", this.valuedeviceName, this.yxdev);
				if (this.valuedeviceName != "") {
					console.log("执行了方案1");
					if (this.yxdev == "") {
						this.yxdev = this.valuedeviceName;
						const existingItem = this.dynamicLists.find((item) => {
							return item.deviceName === this.yxdev;
							// && item.id === this.devitemid; 自己输入的id空
						});

						if (existingItem) {
							// 如果存在相同对象，则增加 number 属性
							existingItem.number++;
						} else {
							// 否则，添加新的对象到 dynamicLists 数组中
							this.dynamicLists.push({
								deviceName: this.yxdev,
								id: "自填",
								number: 1,
							});
						}
					} else {
						const existingItem = this.dynamicLists.find((item) => {
							return item.deviceName === this.valuedeviceName;
							// && item.id === this.devitemid; 自己输入的id空
						});

						if (existingItem) {
							// 如果存在相同对象，则增加 number 属性
							existingItem.number++;
						} else {
							// 否则，添加新的对象到 dynamicLists 数组中
							this.dynamicLists.push({
								deviceName: this.valuedeviceName,
								id: "自填",
								number: 1,
							});
						}
						const existingItems = this.dynamicLists.find((item) => {
							return item.deviceName === this.yxdev;
							// && item.id === this.devitemid; 自己输入的id空
						});

						if (existingItems) {
							// 如果存在相同对象，则增加 number 属性
							existingItem.number++;
						} else {
							// 否则，添加新的对象到 dynamicLists 数组中
							this.dynamicLists.push({
								deviceName: this.yxdev,
								id: this.devitemid,
								number: 1,
							});
						}
					}
				}
				if (this.valuedeviceName == "") {
					console.log("执行了方案2");
					const existingItem = this.dynamicLists.find((item) => {
						return item.deviceName == this.yxdev && item.id == this.devitemid;
					});

					if (existingItem) {
						// 如果存在相同对象，则增加 number 属性
						existingItem.number++;
						console.log("存在相同情况");
					} else {
						// 否则，添加新的对象到 dynamicLists 数组中
						this.dynamicLists.push({
							deviceName: this.yxdev,
							id: this.devitemid,
							number: 1,
						});
					}
					this.yxdev = "";
					this.devitemid = null;
				}

				this.valuedeviceName = "";
				this.devitemid = null;
				this.yxdev = "";
				console.log("添加设备", this.dynamicLists);
			},
			searchs() {
				const debounceDelay = 300;
				// 每次输入时，先清除之前设置的定时器
				clearTimeout(this.debounceTimer);

				// 设置新的定时器
				this.debounceTimer = setTimeout(() => {
					// 在延迟时间后执行搜索操作
					this.search();
				}, debounceDelay);
			},
			search() {
				this.$myRequest({
					url: "/client/appointment/deviceList",
					method: "GET",
					data: {
						deviceName: this.deviceName,
					},
				}).then((res) => {
					this.devlist = res.data;
					// this.deviceName = ''
					// console.log("设备列表", res.data);
				});
				console.log("触发搜索");
			},
			devfn(item) {
				this.devitemid = item.deviceId;
				this.yxdev = item.deviceName;
			},
			del(id) {
				let index = this.dynamicLists.findIndex((v) => v.id === id);
				this.dynamicLists.splice(index, 1);
			},
			add() {
				this.$refs.popup.open();
			},
			setActiveTab(index) {
				this.activeTab = index;
				this.updateUnderlinePosition();
			},
			updateUnderlinePosition() {
				// 根据activeTab计算下划线的位置
				if (this.activeTab == 0) {
					this.underlineLeft = "25%";
				}
				if (this.activeTab == 1) {
					this.underlineLeft = "75%";
				}
			},
			formatTimeRange(startTime, endTime) {
				if (startTime === "" || endTime === "") {
					return "数据错误";
				}

				// 将字符串转换为 Date 对象
				const startDate = new Date(startTime.replace(/-/g, "/")); // 替换所有的'-'号
				const endDate = new Date(endTime.replace(/-/g, "/"));

				// 格式化日期部分
				const startDateString = this.formatDate(startDate); // 格式化开始日期部分

				// 格式化时间部分
				const startTimeString = this.formatTime(startDate); // 格式化开始时间部分
				const endTimeString = this.formatTime(endDate); // 格式化结束时间部分

				// 格式化成所需的字符串
				const formattedTimeRange = `${startDateString} ${startTimeString}~${endTimeString}`;

				return formattedTimeRange;
			},

			// 辅助函数，格式化日期部分
			formatDate(date) {
				const year = date.getFullYear();
				const month = this.padZero(date.getMonth() + 1); // 月份从0开始，需要加1
				const day = this.padZero(date.getDate());

				// 返回格式化后的日期部分字符串
				return `${year}-${month}-${day}`;
			},

			// 辅助函数，格式化时间部分
			formatTime(date) {
				const hours = this.padZero(date.getHours());
				const minutes = this.padZero(date.getMinutes());

				// 返回格式化后的时间部分字符串
				return `${hours}:${minutes}`;
			},

			// 辅助函数，补零函数，用于确保日期时间部分是两位数
			padZero(num) {
				return num.toString().padStart(2, "0");
			},
		},
	};
</script>

<style></style>